﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using Newtonsoft.Json.Linq;


namespace Csharp2Python3
{
    public partial class Form1 : Form
    {
        public static bool running = false;
        SynchronizationContext m_SyncContext = null;
        string filepath = "pythonpid.txt";
        public Form1()
        {
            InitializeComponent();
            m_SyncContext = SynchronizationContext.Current;
            //tabPage_init2("config.json", tabPage1);
            //tabPage_init2("config.json", tabPage2);
            //tabPage_init3("qsid2ip.json", tabPage3);
        }
        private int WM_SYSCOMMAND = 0x112;
        private long SC_MAXIMIZE = 0xF030;
        private long SC_MINIMIZE = 0xF020;
        private long SC_CLOSE = 0xF060;

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_SYSCOMMAND)
            {
                //if (m.WParam.ToInt64() == SC_MAXIMIZE)
                //{
                //    //MessageBox.Show("MAXIMIZE ");
                //    return;
                //}
                //if (m.WParam.ToInt64() == SC_MINIMIZE)
                //{
                //    //MessageBox.Show("MINIMIZE ");
                //    return;
                //}
               
                if (m.WParam.ToInt64() == SC_CLOSE)
                {
                    if (running)
                    {
                        MessageBox.Show("必须先停止指令服务");
                        return;
                    }
                    closePython();
                    this.Dispose(false);
                    Application.Exit();
                }
            }
            base.WndProc(ref m);



        }
        Thread runthread;
        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            
            runthread = new Thread(runstart, 10);
            runthread.IsBackground = true;
            running = true;
            runthread.Start();


            for (int i = 0; i < 3; i++)
            {
                button1.Text = "初始化中..." + (3 - i) + "...";
                button1.Update();
                Thread.Sleep(1000);
            }
            button1.Text = "通达信指令监控中";
            button1.Update();
            button2.Enabled = true;
            
          
            running = true;
          
        }

        private void button2_Click(object sender, EventArgs e)
        {
            button2.Enabled = false;
            button1.Enabled = true;
            //textBox1.Enabled = true;
            //textBox3.Enabled = true;
            //numericUpDown1.Enabled = true;
            running = false;
            button1.Text = "开始";
            button1.Update();
            closePython();

        }
        public void closePython()
        {
            if (System.IO.File.Exists(filepath))
            {
                int pid = Int32.Parse(FileHelper.ReadFile(filepath));
                if (pid > 0)
                {
                    try
                    {
                        Process p = Process.GetProcessById(pid);
                        p.Kill();
                        p.Close();
                        FileHelper.FileDel(filepath);
                    }
                    catch (Exception)
                    {

                    }
                }

            }
        }


        public void runstart()
        {
            //richTextBox1.Text = "";
            Process p = new Process();
            string path = "ttt.py";
            string sArguments = path;
            p.StartInfo.FileName = @"C:\Program Files (x86)\Python37-32\python.exe";
           // p.StartInfo.FileName = @"lib\python.exe";
            p.StartInfo.Arguments = sArguments;//python命令的参数
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardInput = false;
            p.StartInfo.RedirectStandardError = false;
            p.StartInfo.CreateNoWindow = true;

            //p.EnableRaisingEvents = true;
            p.Start();//启动进程
           
            p.BeginOutputReadLine();
            p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
            p.WaitForExit();

        }
        private void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.Data))
            {
                //AppendLogLine(Environment.NewLine);
                //m_SyncContext.Post(SetTextSafePost, Environment.NewLine);
                m_SyncContext.Post(SetTextSafePost, e.Data);
            }
        }
        public void AppendLogLine(String logString)
        {
            int len = this.richTextBox1.Text.Trim().Length;
            if (len == 0)
            {
                this.richTextBox1.Text = logString;
            }
            else
            {
                //文字超过1000，清空
                if (len > 100000) ClearLog();
                this.richTextBox1.AppendText("\n");
                this.richTextBox1.AppendText(logString);
                richTextBox1.Focus();
                //设置光标的位置到文本尾 
                this.richTextBox1.Select(this.richTextBox1.TextLength, 0);
                //滚动到控件光标处 
                this.richTextBox1.ScrollToCaret();
                //this.richTextBox1.Update();
                //MessageBox.Show(logString);
            }
        }

        public void ClearLog()
        {
            richTextBox1.Text = "";
        }


        public static string laststr = "";
       

        private void SetTextSafePost(object text)
        {
            AppendLogLine(text.ToString());
         
        }
        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
           
        }
        private void contextMenuStrip1_Opening(object sender, EventArgs e)
        {

        }
        

        private void Form1_Load(object sender, EventArgs e)
        {
            closePython();
        }
        private void Form1_FormClosing(object sender, FormClosedEventArgs e)
        {
           // Console.WriteLine("1111");
            closePython();
            Process p = Process.GetCurrentProcess();
            if (p != null)
            {
                p.Kill();
                p.Close();
            }
            System.Environment.Exit(0);
        }
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)

        {

         
            // p.Close();
            //runthread.
            //Form1.runthread.Dispose();
            // this.logthread;
            closePython();
            //Process p = Process.GetCurrentProcess();
            //if (p != null)
            //{
            //    p.Kill();
            //}
            System.Environment.Exit(0);
            Dispose();
            Application.Exit();
            
        }

        public void tabPage_init2(string jsonfile, TabPage page)
        {
            var dbconfig = FileHelper.ReadFile(jsonfile);
            //Console.WriteLine(dbconfig);
            JObject obj = JObject.Parse(dbconfig);
            TableLayoutPanel layoiutpan = new TableLayoutPanel();
            //layoiutpan.set
            layoiutpan.ColumnCount = 2;
            layoiutpan.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            layoiutpan.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            // layoiutpan.Location = new System.Drawing.Point(173, 96);
            //layoiutpan.Name = "tableLayoutPanel1";
            layoiutpan.RowCount = obj.Children().Count();
            //layoiutpan.Size = new System.Drawing.Size(200, 300);
            layoiutpan.AutoSize = true;
            layoiutpan.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            layoiutpan.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            layoiutpan.TabIndex = 2;

            //Label l0 = new Label();
            //l0.Text = "123";
            //layoiutpan.Controls.Add(l0, 0, 0);
            //layoiutpan.Controls.Add(new TextBox(), 1, 0);

            int column = 0;int row=0;

            //tabPage1.Controls.Add(l0);
            //Label l1 = new Label();
            //l1.Text = "456";
            //layoiutpan.Controls.Add(l1, 0, 1);
            //layoiutpan.Controls.Add(new TextBox(), 1, 1);
            //layoiutpan.RowCount = 6;
            foreach (JProperty item in obj.Children())
            {
                //obj.Name
              //  Console.WriteLine(item.Name);
                Label lable = new Label();
                lable.Text = item.Name;
                lable.TextAlign = ContentAlignment.MiddleCenter;
                layoiutpan.Controls.Add(lable, 0, column);
                TextBox box=new TextBox();
                box.Text = item.Value.ToString();
                box.TextAlign = HorizontalAlignment.Left;
                box.ReadOnly = true;
                layoiutpan.Controls.Add(box, 1, column);
                column++;
            }
            page.Controls.Add(layoiutpan);
            //DbConfig config= Json.JsonParser.Deserialize<DbConfig>(dbconfig);
            //Console.WriteLine(config);

        }
        public void tabPage_init3(string jsonfile, TabPage page)
        {
            var dbconfig = FileHelper.ReadFile(jsonfile);

            Dictionary<string, Qsid> diction =  Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, Qsid>>(dbconfig);
            int column = 0;//行
            int row = 0;//列
            JObject obj = JObject.Parse(dbconfig);
            TableLayoutPanel layoiutpan = new TableLayoutPanel();
            //layoiutpan.set
            layoiutpan.ColumnCount = 4;
            layoiutpan.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            layoiutpan.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
            // layoiutpan.Location = new System.Drawing.Point(173, 96);
            //layoiutpan.Name = "tableLayoutPanel1";
            layoiutpan.RowCount = obj.Children().Count();
            //layoiutpan.Size = new System.Drawing.Size(200, 300);
            layoiutpan.AutoSize = true;
            //layoiutpan.Height = 900;
            layoiutpan.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            layoiutpan.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            layoiutpan.TabIndex = 3;
            //layoiutpan.AutoScroll = true;
            int first_w = 30;
            Label lable1 = new Label();
            lable1.Text ="qsid";
            lable1.Width = first_w;
            lable1.TextAlign = ContentAlignment.MiddleCenter;

            Label lable2 = new Label();
            lable2.Text = "name";
            lable2.TextAlign = ContentAlignment.MiddleCenter;


            Label lable3 = new Label();
            lable3.Text = "ip";
            lable3.TextAlign = ContentAlignment.MiddleCenter;


            Label lable4 = new Label();
            lable4.Text = "port";
            lable4.TextAlign = ContentAlignment.MiddleCenter;
            layoiutpan.Controls.Add(lable1, column, row);
                column++;
            layoiutpan.Controls.Add(lable2, column, row);
            column++;
            layoiutpan.Controls.Add(lable3, column, row); 
            column++;
            layoiutpan.Controls.Add(lable4, column, row);
            column = 0;
            row++;


            foreach(string key in diction.Keys)
            {
                Qsid qsid = diction[key];

                TextBox box1 = new TextBox();
                box1.Text = key;
                box1.Width = first_w;
                box1.TextAlign = HorizontalAlignment.Left;

                TextBox box2 = new TextBox();
                box2.Text = qsid.name;
                box2.TextAlign = HorizontalAlignment.Left;

                TextBox box3 = new TextBox();
                box3.Text = qsid.ip;
                box3.TextAlign = HorizontalAlignment.Left;

                TextBox box4 = new TextBox();
                box4.Text = qsid.port.ToString();
                box4.TextAlign = HorizontalAlignment.Left;

                box1.ReadOnly = true;
                box2.ReadOnly = true;
                box3.ReadOnly = true;
                box4.ReadOnly = true;

                layoiutpan.Controls.Add(box1, column, row);
                column++;
                layoiutpan.Controls.Add(box2, column, row);
                column++;
                layoiutpan.Controls.Add(box3, column, row);
                column++;
                layoiutpan.Controls.Add(box4, column, row);
                column = 0;
                row++;
            }

            page.Height = 900;
            page.Controls.Add(layoiutpan);

        }
    

        private void button3_Click(object sender, EventArgs e)
        {

        }

        private void ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormSql sqlform = new FormSql();
            sqlform.ShowDialog();
            //this.Show();
        }

        private void qSIDToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormQsid qsidform = new FormQsid();
            qsidform.ShowDialog();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutForm qsidform = new AboutForm();
            qsidform.ShowDialog();
        }
    }
}



